package com.zhouyu.mybatis.spring;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 通过FactoryBean将mybatis生成的Mapper对象添加到Spring容器中
 */
public class MyBatisFactoryBean implements FactoryBean {

	private Class clazz;
	private SqlSession sqlSession;

	// 通过构造函数指定要getMapper的类
	public MyBatisFactoryBean(Class clazz) {
		this.clazz = clazz;
	}

	// 由用户通过@Bean生成SqlSessionFactory后，由Spring依赖注入进来
	@Autowired
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSession = sqlSessionFactory.openSession();
		sqlSessionFactory.getConfiguration().addMapper(clazz);
	}

	@Override
	public Object getObject() throws Exception {
		return sqlSession.getMapper(clazz);
	}

	@Override
	public Class<?> getObjectType() {
		return clazz;
	}
}
